package com.hao.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.LinkedList;

/**
 * 队列管理器，有内存管理的作用。
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
public class QueueManager {
    private static final Integer MAX_SIZE = 30;//允许30个进程同时进行

    private LinkedList<PCBProcess> readyQueue = new LinkedList<>();//就绪队列

    public PCBProcess createProcess() {
        //创建新进程失败，返回空
        if (readyQueue.size() >= QueueManager.MAX_SIZE) {
            return null;
        }
        //填入信息
        PCBProcess pcbProcess = new PCBProcess();
        pcbProcess.setName(getName());
        pcbProcess.setPri(getRandomInteger(10));
        pcbProcess.setTime(getRandomInteger(20));
        pcbProcess.setStatus(0);
        readyQueue.add(pcbProcess);

        return pcbProcess;
    }

    //生成 1~n 之间的整数值
    private int getRandomInteger(int n) {
        return (int)(Math.random() * n + 1);
    }

    public void printReadyQueue() {
        System.out.println("-------------当前就绪队列-------------");
        for (PCBProcess pcbProcess : readyQueue) {
            System.out.println(pcbProcess);
        }
    }

    public int getName() {
        while (true) {
            int name = getRandomInteger(100);
            int flag = 1;
            for (PCBProcess pcbProcess : readyQueue) {
                if (pcbProcess.getName().equals(name)) {
                    flag = 0;
                    break;
                }
            }//for
            if (flag == 1) {
                return name;//找到不重复的，退出
            }
        }
    }
}
